package org.microframework.cloud.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.microframework.base.core.domain.R;
import org.microframework.cloud.system.model.domain.User;
import org.microframework.cloud.system.service.ISysUserService;
import org.microframework.cloud.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户管理控制器
 * 使用JFinal ActiveRecord实现数据访问
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController {

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private SysUserServiceImpl userServiceImpl;
    
    /**
     * 获取用户列表
     * 使用JFinal Db.find方法查询记录列表
     */
    @GetMapping
    @Operation(summary = "获取用户列表")
    public R<List<Record>> list() {
        List<Record> users = Db.find("SELECT id, username, nickname, email, mobile, status, create_time FROM sys_user WHERE del_flag = 0");
        return R.ok(users);
    }
    
    /**
     * 获取用户详情
     * 使用JFinal Model.findById方法
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情")
    public R<?> get(@PathVariable("id") String id) {
        org.microframework.cloud.system.model.domain.User user = 
            org.microframework.cloud.system.model.domain.User.dao.findById(id);
            
        if (user == null) {
            return R.fail("用户不存在");
        }
        
        // 不返回密码
        user.remove("password");
        
        return R.ok(user);
    }
    
    /**
     * 创建用户
     * 使用JFinal ActiveRecord的save方法
     */
    @PostMapping
    @Operation(summary = "创建用户")
    public R<?> create(@RequestBody User userReq) {
        // 检查用户名是否存在
        Optional<User> existingUser = userService.findByUsername(userReq.getUsername());
        if (existingUser.isPresent()) {
            return R.fail("用户名已存在");
        }
        
        PasswordEncoder passwordEncoder=PasswordEncoderFactories.createDelegatingPasswordEncoder();
        // 设置用户信息
        User user = new User();
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setUsername(userReq.getUsername());
        user.setPassword(passwordEncoder.encode(userReq.getPassword()));
        user.setNickname(userReq.getNickname());
        user.setEmail(userReq.getEmail());
        user.setMobile(userReq.getMobile());
        user.setStatus(0); // 默认启用
        user.setDelFlag(0); // 未删除
        user.setCreateTime(new Date());
        user.setCreateBy("admin");
        
        // 使用实现类中的自定义方法创建用户
        boolean success = userServiceImpl.createUser(user);
        
        if (success) {
            return R.ok();
        } else {
            return R.fail("创建用户失败");
        }
    }
    
    /**
     * 更新用户
     * 使用JFinal ActiveRecord的update方法
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新用户")
    public R<?> update(@PathVariable("id") String id, @RequestBody User userReq) {
        // 查询用户
        org.microframework.cloud.system.model.domain.User user = 
            org.microframework.cloud.system.model.domain.User.dao.findById(id);
            
        if (user == null) {
            return R.fail("用户不存在");
        }
        
        // 更新用户信息
        user.setNickname(userReq.getNickname());
        user.setEmail(userReq.getEmail());
        user.setMobile(userReq.getMobile());
        if (userReq.getStatus() != null) {
            user.setStatus(userReq.getStatus());
        }
        user.setUpdateTime(new Date());
        user.setUpdateBy("admin");
        
        // 使用ActiveRecord的update方法更新用户
        boolean success = user.update();
        
        if (success) {
            return R.ok();
        } else {
            return R.fail("更新用户失败");
        }
    }
    
    /**
     * 删除用户（逻辑删除）
     * 使用JFinal Db.update方法
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    public R<?> delete(@PathVariable("id") String id) {
        // 逻辑删除用户
        int affected = Db.update("UPDATE sys_user SET del_flag = 1, update_time = ?, update_by = ? WHERE id = ?", 
                new Date(), "admin", id);
                
        if (affected > 0) {
            return R.ok();
        } else {
            return R.fail("删除用户失败");
        }
    }
    
    /**
     * 重置密码
     * 结合使用JFinal和服务层方法
     */
    @PutMapping("/{id}/password/reset")
    @Operation(summary = "重置密码")
    public R<?> resetPassword(@PathVariable("id") String id, @RequestBody String password) {
        // 查询用户
        org.microframework.cloud.system.model.domain.User user = 
            org.microframework.cloud.system.model.domain.User.dao.findById(id);
            
        if (user == null) {
            return R.fail("用户不存在");
        }
        PasswordEncoder passwordEncoder=PasswordEncoderFactories.createDelegatingPasswordEncoder();

        // 更新密码
        user.setPassword(passwordEncoder.encode(password));
        user.setUpdateTime(new Date());
        user.setUpdateBy("admin");
        
        // 使用ActiveRecord的update方法更新用户
        boolean success = user.update();
        
        if (success) {
            return R.ok();
        } else {
            return R.fail("重置密码失败");
        }
    }
} 